//package com.spider.im.chat.dao;
//
//
//
//import com.spider.im.chat.model.ChatMessage;
//import com.spider.im.chat.utils.DatabaseManager;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import java.sql.*;
//import java.util.ArrayList;
//import java.util.List;
//
//public class ChatMessageDAO {
//    private static final Logger logger = LoggerFactory.getLogger(ChatMessageDAO.class);
//
//    // 发送消息（文本或文件）
//    public boolean sendMessage(ChatMessage message) {
//        String sql = "INSERT INTO chat_messages (sender_id, receiver_id, message, message_type, file_url, sender_status, receiver_status) VALUES (?, ?, ?, ?, ?, ?, ?)";
//
//        try (Connection conn = DatabaseManager.getConnection();
//             PreparedStatement stmt1 = conn.prepareStatement(sql);
//             PreparedStatement stmt2 = conn.prepareStatement(sql)) {
//
//            // 发送方数据
//            stmt1.setLong(1, message.getSenderId());
//            stmt1.setLong(2, message.getReceiverId());
//            stmt1.setString(3, message.getMessage());
//            stmt1.setString(4, message.getMessageType());
//            stmt1.setString(5, message.getFileUrl());
//            stmt1.setString(6, "normal");
//            stmt1.setString(7, "unread");
//
//            // 接收方数据
//            stmt2.setLong(1, message.getSenderId());
//            stmt2.setLong(2, message.getReceiverId());
//            stmt2.setString(3, message.getMessage());
//            stmt2.setString(4, message.getMessageType());
//            stmt2.setString(5, message.getFileUrl());
//            stmt2.setString(6, "normal");
//            stmt2.setString(7, "unread");
//
//            int rows1 = stmt1.executeUpdate();
//            int rows2 = stmt2.executeUpdate();
//
//            return rows1 > 0 && rows2 > 0;
//        } catch (SQLException e) {
//            logger.error("Error sending message: {}", e.getMessage());
//            return false;
//        }
//    }
//
//    // 获取用户发送的消息
//    public List<ChatMessage> getSentMessages(Long senderId) {
//        String sql = "SELECT * FROM chat_messages WHERE sender_id = ? AND sender_status != 'deleted' ORDER BY created_at DESC";
//        return getMessages(senderId, sql);
//    }
//
//    // 获取用户接收的消息
//    public List<ChatMessage> getReceivedMessages(Long receiverId) {
//        String sql = "SELECT * FROM chat_messages WHERE receiver_id = ? AND receiver_status != 'deleted' ORDER BY created_at DESC";
//        return getMessages(receiverId, sql);
//    }
//
//    // 公共查询方法
//    private List<ChatMessage> getMessages(Long userId, String sql) {
//        List<ChatMessage> messages = new ArrayList<>();
//
//        try (Connection conn = DatabaseManager.getConnection();
//             PreparedStatement stmt = conn.prepareStatement(sql)) {
//
//            stmt.setLong(1, userId);
//            ResultSet rs = stmt.executeQuery();
//
//            while (rs.next()) {
//                messages.add(extractMessage(rs));
//            }
//        } catch (SQLException e) {
//            logger.error("Error fetching messages: {}", e.getMessage());
//        }
//
//        return messages;
//    }
//
//    // 标记消息为已读
//    public boolean markAsRead(Long receiverId) {
//        String sql = "UPDATE chat_messages SET receiver_status = 'read' WHERE receiver_id = ? AND receiver_status = 'unread'";
//
//        try (Connection conn = DatabaseManager.getConnection();
//             PreparedStatement stmt = conn.prepareStatement(sql)) {
//
//            stmt.setLong(1, receiverId);
//            int rowsAffected = stmt.executeUpdate();
//            return rowsAffected > 0;
//        } catch (SQLException e) {
//            logger.error("Error marking messages as read: {}", e.getMessage());
//            return false;
//        }
//    }
//
//    // 删除自己发送的消息
//    public boolean deleteSentMessages(Long senderId) {
//        String sql = "UPDATE chat_messages SET sender_status = 'deleted' WHERE sender_id = ?";
//
//        try (Connection conn = DatabaseManager.getConnection();
//             PreparedStatement stmt = conn.prepareStatement(sql)) {
//
//            stmt.setLong(1, senderId);
//            int rowsAffected = stmt.executeUpdate();
//            return rowsAffected > 0;
//        } catch (SQLException e) {
//            logger.error("Error deleting sent messages: {}", e.getMessage());
//            return false;
//        }
//    }
//
//    // 删除自己收到的消息
//    public boolean deleteReceivedMessages(Long receiverId) {
//        String sql = "UPDATE chat_messages SET receiver_status = 'deleted' WHERE receiver_id = ?";
//
//        try (Connection conn = DatabaseManager.getConnection();
//             PreparedStatement stmt = conn.prepareStatement(sql)) {
//
//            stmt.setLong(1, receiverId);
//            int rowsAffected = stmt.executeUpdate();
//            return rowsAffected > 0;
//        } catch (SQLException e) {
//            logger.error("Error deleting received messages: {}", e.getMessage());
//            return false;
//        }
//    }
//
//    // 辅助方法：从结果集中提取消息
//    private ChatMessage extractMessage(ResultSet rs) throws SQLException {
//        ChatMessage message = new ChatMessage(
//                rs.getLong("sender_id"),
//                rs.getLong("receiver_id"),
//                rs.getString("message"),
//                rs.getString("message_type"),
//                rs.getString("file_url")
//        );
//        message.setId(rs.getLong("id"));
//        message.setSenderStatus(rs.getString("sender_status"));
//        message.setReceiverStatus(rs.getString("receiver_status"));
//        message.setCreatedAt(rs.getTimestamp("created_at").toLocalDateTime());
//        return message;
//    }
//}
